package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 菜品
 *
 * @Author Yang
 * @Date 2023/3/5 10:55
 */
@RestController
@Transactional
@Api(tags = "菜品")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    //分页查询,并携带菜品名
    @GetMapping("/dish/page")
    public ResultInfo findByPage(@RequestParam(value = "page") Integer pageNum,
                                 @RequestParam(value = "pageSize") Integer pageSize,
                                 String name) {
        Page<Dish> dishPage = dishService.findByPage(pageNum, pageSize, name);
        return ResultInfo.success(dishPage);
    }

    //新增
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish) {
        dishService.save(dish);

        // 清理缓存
        String dishKey = "dish_"+dish.getCategoryId();
        redisTemplate.delete(dishKey);

        return ResultInfo.success();
    }

    // 抽取删除公共方法
    private void clean(String key) {
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }


    //ID回显
    @GetMapping("/dish/{dishId}")
    public ResultInfo findById(@PathVariable("dishId") Long dishId) {
        Dish dish = dishService.findById(dishId);
        return ResultInfo.success(dish);
    }


    //修改

    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish) {
        dishService.update(dish);


        // 清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }

    //批量起售停售
    @PostMapping("/dish/status/{status}")
    public ResultInfo updateStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        dishService.updateStatus(status, ids);


        // 清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }

    //批量删除
    @DeleteMapping("/dish")
    public ResultInfo deleteByIds(@RequestParam List<Long> ids) {
        dishService.deleteByIds(ids);


        // 清理缓存
        clean("dish_*");
        return ResultInfo.success();
    }

    //ID回显
    @GetMapping("/dish/list")
    public ResultInfo findListBySetmeal(Long categoryId,String name){
        List<Dish> dishes = dishService.findListBySetmeal(categoryId,name);
        return ResultInfo.success(dishes);
    }
}
